package com.suli.account.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scenic.util.JWTUtils;
import com.suli.account.entity.User;
import com.suli.account.entity.UserRole;
import com.suli.account.entity.VO.UserVO;
import com.suli.account.enums.Status;
import com.suli.account.enums.UserType;
import com.suli.account.mapper.UserMapper;
import com.suli.account.mapper.UserRoleMapper;
import com.suli.account.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author SuLi
 * @since 2022-03-19
 */
@Service
@Transactional
@SuppressWarnings("all")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Override
    public Map<String,Integer> registerUser(User user) {
        Map<String,Integer> map =new HashMap<>();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name", user.getUserName());
        User user1 = userMapper.selectOne(queryWrapper);
        if(!ObjectUtils.isEmpty(user1)){
            map.put("registerStatus",0);
            return map;
        }
        QueryWrapper<User> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("user_email", user.getUserEmail());
        User user2 = userMapper.selectOne(queryWrapper1);
        if(!ObjectUtils.isEmpty(user2)){
            map.put("registerStatus",1);
            return map;
        }
        String s = DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes(StandardCharsets.UTF_8));
        user.setUserPassword(s);
        userMapper.insert(user);
        UserRole role=new UserRole();
        role.setUserId(user.getUserId());
        role.setRoleId(UserType.USER);
        userRoleMapper.insert(role);
        map.put("registerStatus",2);
        return map;
    }

    @Override
    public Map<String, String> login(String username,String password) {
        String regEx="^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
        boolean matches = Pattern.matches(regEx, username);
        String s = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        Map<String,String> map=new HashMap<>();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        //如果是邮箱
        if(matches){
            queryWrapper.eq("user_email", username);
            User user = userMapper.selectOne(queryWrapper);
            if(!ObjectUtils.isEmpty(user)){
                if(user.getUserFreeze()== Status.FREEZE){
                    map.put("message", "账户已冻结");
                    return map;
                }
                if(user.getUserPassword().equals(s)){
                    List<String> roleName = userRoleMapper.getRoleName(user.getUserId());
                    String token = JWTUtils.getJwtToken(user.getUserName(),
                            roleName, user.getUserId(), user.getUserAvatar(), user.getUserEmail());
                    map.put("message", "登录成功");
                    map.put("token", token);
                    return map;
                }
                map.put("message", "密码错误");
                return map;
            }
            map.put("message", "账号不存在");
            return map;
        }else{
            queryWrapper.eq("user_name", username);
            User user = userMapper.selectOne(queryWrapper);
            if(!ObjectUtils.isEmpty(user)){
                if(user.getUserFreeze()== Status.FREEZE){
                    map.put("message", "账户已冻结");
                    return map;
                }
                if(user.getUserPassword().equals(s)){
                    List<String> roleName = userRoleMapper.getRoleName(user.getUserId());
                    String token = JWTUtils.getJwtToken(user.getUserName(), roleName, user.getUserId(), user.getUserAvatar(), user.getUserEmail());
                    map.put("message", "登录成功");
                    map.put("token", token);
                    return map;
                }
                map.put("message", "密码错误");
                return map;
            }
            map.put("message", "账号不存在");
            return map;
        }
    }

    @Override
    public Map<String, Object> getUsers(Long page, Long limit) {
        page=(page-1)*10;
        Integer total = userMapper.getTotalUser();
        List<UserVO> users = userMapper.getUsers(page, limit);
        Map<String, Object> map=new HashMap<>();
        map.put("total", total);
        map.put("userList", users);
        return map;
    }

    @Override
    public Map<String, Object> getUserInfo(String info) {
        User user = getUser(info);
        Map<String,Object> map=new HashMap<>();
        map.put("user", user);
        return map;
    }

    private User getUser(String info){
         if(Pattern.matches("\\d+", info)){
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("user_id", info);
            User user = userMapper.selectOne(queryWrapper);
            return user;
        }else if(Pattern.matches("[a-zA-Z]+", info)){
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("user_name", info);
            User user = userMapper.selectOne(queryWrapper);
            return user;
        }else {
             QueryWrapper<User> queryWrapper=new QueryWrapper<>();
             queryWrapper.eq("user_email", info);
             User user = userMapper.selectOne(queryWrapper);
             return user;
         }
    }
}
